﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FAQFrameworks
{
    public class FilePagerProvider
    {
        BinaryReader binaryReader;
        FileStream stream;

        public FilePagerProvider(string filePath)
        {
            stream = new FileStream(filePath, FileMode.Open);

            binaryReader = new BinaryReader(stream);
        }

        public int PageSize
        {
            get;
            set;
        }

        public IEnumerable<int> ListPage(int pageIndex)
        {
            stream.Seek(pageIndex * 4 * PageSize,
                SeekOrigin.Begin);
            int[] ints = new int[this.PageSize];
            for (int i = 0; i < this.PageSize; i++)
            {
                ints[i] = binaryReader.ReadInt32();
            }

            return ints;
        }

        public int Count
        {
            get
            {
                return (int)stream.Length / 4;
            }
        }

        public int PageCount
        {
            get
            {
                int pageCount = this.Count / PageSize;
                if (pageCount % PageSize != 0)
                {
                    pageCount++;
                }

                return pageCount;
            }
        }

        public static void AppendInt(string filePath, int index)
        {
            FileStream stream
                 = new FileStream(filePath, FileMode.Append);

            BinaryWriter binaryWriter = new BinaryWriter(stream);

            binaryWriter.Write(index);
        }
    }
}
